#include "SudokuBoard.h"
#include <QVBoxLayout>
#include <QFrame>

SudokuBoard::SudokuBoard(QWidget *parent)
    : QWidget(parent)
    , m_gridLayout(nullptr)
    , m_difficulty(1)
{
    setupUI();
}

void SudokuBoard::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(10, 10, 10, 10);

    // 创建3x3的大宫格网格
    QGridLayout *bigGridLayout = new QGridLayout();
    bigGridLayout->setSpacing(4);  // 宫格之间的间距
    bigGridLayout->setContentsMargins(0, 0, 0, 0);

    // 创建9个大宫格（每个包含3x3小单元格）
    for (int bigRow = 0; bigRow < 3; ++bigRow) {
        for (int bigCol = 0; bigCol < 3; ++bigCol) {
            // 创建大宫格的容器
            QFrame *bigFrame = new QFrame();
            bigFrame->setFrameStyle(QFrame::Box);
            bigFrame->setLineWidth(3);
            bigFrame->setMidLineWidth(3);
            bigFrame->setStyleSheet("QFrame { border: 3px solid #2c3e50; background-color: transparent; }");

            // 创建大宫格内部的小网格
            QGridLayout *smallGridLayout = new QGridLayout(bigFrame);
            smallGridLayout->setSpacing(1);
            smallGridLayout->setContentsMargins(2, 2, 2, 2);

            // 填充3x3小单元格
            for (int smallRow = 0; smallRow < 3; ++smallRow) {
                for (int smallCol = 0; smallCol < 3; ++smallCol) {
                    int actualRow = bigRow * 3 + smallRow;
                    int actualCol = bigCol * 3 + smallCol;

                    SudokuCell *cell = new SudokuCell(actualRow, actualCol, this);
                    m_cells[actualRow][actualCol] = cell;

                    // 将单元格添加到小网格，并居中
                    smallGridLayout->addWidget(cell, smallRow, smallCol);
                    smallGridLayout->setAlignment(cell, Qt::AlignCenter);

                    connect(cell, &SudokuCell::valueChanged, this, &SudokuBoard::onCellValueChanged);
                }
            }

            // 将大宫格添加到主布局
            bigGridLayout->addWidget(bigFrame, bigRow, bigCol);
        }
    }

    mainLayout->addLayout(bigGridLayout);

    // 初始化状态数组
    m_currentState = QVector<QVector<int>>(BOARD_SIZE, QVector<int>(BOARD_SIZE, 0));
}

void SudokuBoard::initializeBoard(const QVector<QVector<int>>& puzzle, 
                                 const QVector<QVector<int>>& solution)
{
    m_initialPuzzle = puzzle;
    m_solution = solution;
    m_currentState = puzzle;
    
    for (int row = 0; row < BOARD_SIZE; ++row) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            int value = puzzle[row][col];
            bool isFixed = (value != 0);
            m_cells[row][col]->setInitialValue(value, isFixed);
        }
    }
}

void SudokuBoard::onCellValueChanged(int row, int col, int value)
{
    m_currentState[row][col] = value;
    
    // 检查输入是否有效
    if (value != 0 && !isValidPlacement(row, col, value)) {
        m_cells[row][col]->setCorrect(false);
    } else {
        m_cells[row][col]->setCorrect(true);
    }
    
    emit cellValueChanged(row, col, value);
    
    // 检查是否完成
    if (isComplete() && checkSolution()) {
        emit puzzleSolved();
    }
}

bool SudokuBoard::checkSolution()
{
    for (int row = 0; row < BOARD_SIZE; ++row) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            if (m_currentState[row][col] != m_solution[row][col]) {
                return false;
            }
        }
    }
    return true;
}

bool SudokuBoard::isComplete() const
{
    for (int row = 0; row < BOARD_SIZE; ++row) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            if (m_currentState[row][col] == 0) {
                return false;
            }
        }
    }
    return true;
}

bool SudokuBoard::isValidPlacement(int row, int col, int value) const
{
    // 检查行
    for (int c = 0; c < BOARD_SIZE; ++c) {
        if (c != col && m_currentState[row][c] == value) {
            return false;
        }
    }
    
    // 检查列
    for (int r = 0; r < BOARD_SIZE; ++r) {
        if (r != row && m_currentState[r][col] == value) {
            return false;
        }
    }
    
    // 检查3x3宫格
    int startRow = (row / 3) * 3;
    int startCol = (col / 3) * 3;
    for (int r = startRow; r < startRow + 3; ++r) {
        for (int c = startCol; c < startCol + 3; ++c) {
            if (r != row && c != col && m_currentState[r][c] == value) {
                return false;
            }
        }
    }
    
    return true;
}

void SudokuBoard::setLevelDifficulty(int difficulty)
{
    m_difficulty = difficulty;
}

void SudokuBoard::clearBoard()
{
    for (int row = 0; row < BOARD_SIZE; ++row) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            m_cells[row][col]->clear();
        }
    }
    m_currentState = QVector<QVector<int>>(BOARD_SIZE, QVector<int>(BOARD_SIZE, 0));
}

void SudokuBoard::resetBoard()
{
    for (int row = 0; row < BOARD_SIZE; ++row) {
        for (int col = 0; col < BOARD_SIZE; ++col) {
            m_cells[row][col]->reset();
        }
    }
    m_currentState = m_initialPuzzle;
}

int SudokuBoard::getCellValue(int row, int col) const
{
    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
        return m_currentState[row][col];
    }
    return 0;
}

void SudokuBoard::setCellValue(int row, int col, int value)
{
    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
        m_cells[row][col]->setText(value > 0 ? QString::number(value) : "");
        m_currentState[row][col] = value;
    }
}

QVector<QVector<int>> SudokuBoard::getCurrentState() const
{
    return m_currentState;
}

void SudokuBoard::updateCellAppearance()
{
    // 可以在这里添加更复杂的视觉反馈
}
